package com.stephenone.servicedemo;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.stephenone.handlerdemo.R;

public class MessengerActivity extends AppCompatActivity {
    Messenger mService;

    private Handler clientHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MessengerService.MSG_REPLY_HELLO:
                    Toast.makeText(MessengerActivity.this,"收到Service发来的replySayHello哈哈哈",
                            Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    private Messenger clientMesssenger = new Messenger(clientHandler);
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = new Messenger(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_messenger);

    }

    public void onSendClick(View v){
        Message message =  Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
        message.replyTo = clientMesssenger;
        try {
            mService.send(message);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        bindService(new Intent(MessengerActivity.this,MessengerService.class),conn, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unbindService(conn);
    }
}
